import { useCallback, useEffect } from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { getAccessToken } from '@/utils/storage';
import { validateToken, isInvalidToken as isRefreshToken, refreshAccessToken } from '@/utils/token';

function AuthRoute({ children }) {
    // url白名单
    const url = ['/login', '/register', '/404', '/login/wechat', '/login/phone', '/login/email'];

    const location = useLocation();

    // 检测登陆
    const checkLogin = useCallback(() => {
        let accessToken = getAccessToken();
        if (accessToken) {
            if (validateToken(accessToken)) {
                if (!isRefreshToken(accessToken)) {
                    refreshAccessToken();
                }
            } else {
                refreshAccessToken();
            }
            return true;
        }
        return false;
    }, []);

    // 添加定时刷新token
    useEffect(() => {
        // 组件初始化时，执行一次
        const intervalId = setInterval(() => {
            refreshAccessToken();
        }, 60 * 60 * 1000); // 每一个小时刷新一次

        // 组件卸载时，销毁定时器
        return () => {
            clearInterval(intervalId);
        };
    }, []);

    if (!url.includes(location.pathname) && !checkLogin()) {
        return <Navigate to='/login' replace />;
    }

    return children;
}

export default AuthRoute;